package com.meteor.downloader.videodownloader

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.google.android.gms.ads.MobileAds
import com.hjq.language.MultiLanguages
import com.meteor.downloader.videodownloader.activity.MdmRootActivity
import com.meteor.downloader.videodownloader.activity.downloader.MdmInputLinkActivity
import com.meteor.downloader.videodownloader.clueft.MdmTokenMeans
import com.meteor.downloader.videodownloader.utils.ApplicationMdmUtils
import com.meteor.downloader.videodownloader.utils.DataManagerMdmUtils
import com.meteor.downloader.videodownloader.utils.MdmTotalUtils
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_APP_FROM_VALUE
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_CUR_DATE_TIME
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_CUR_NOTIFY_AD_SHOW
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_TIME_FIRST_DO
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MdmDealApplication : Application(), Application.ActivityLifecycleCallbacks {
    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(MultiLanguages.attach(newBase))
    }

    companion object {
        lateinit var mMdmContext: Context

        var mAppMdmOpen = false
        val mListActivityList = mutableListOf<Activity>()
        var mMdmCl = false

        var mMdmRootActivity: MdmRootActivity? = null
    }

    override fun onCreate() {
        super.onCreate()
        mMdmContext = this
        MultiLanguages.init(this)
        registerActivityLifecycleCallbacks(this)

        if (DataManagerMdmUtils.getDataKeyMdm(MDM_TIME_FIRST_DO, 0L) == 0L) {
            DataManagerMdmUtils.setDataKeyMdm(MDM_TIME_FIRST_DO, System.currentTimeMillis() + 1)
        }
        CoroutineScope(Dispatchers.IO).launch {
            launch {
                try {
                    MobileAds.initialize(applicationContext)
                } catch (_: Exception) {

                }
            }
            launch {
                //remote config
                ApplicationMdmUtils.getConfigMdmData(this@MdmDealApplication)
            }
            launch {
                //归因
                getAppFromValue()
            }
            launch {
                //通知 action
                ApplicationMdmUtils.initReceiverAction(applicationContext)
            }
            launch {
                MdmTokenMeans.getMdmTokenTime(applicationContext)
            }
        }

        val dateTime = DataManagerMdmUtils.getDataKeyMdm(MDM_CUR_DATE_TIME, 0L)
        if (MdmTotalUtils.getMdmFullDate(dateTime) != MdmTotalUtils.getMdmFullDate(System.currentTimeMillis())) {
            DataManagerMdmUtils.setDataKeyMdm(MDM_CUR_DATE_TIME, System.currentTimeMillis())
            DataManagerMdmUtils.setDataKeyMdm(MDM_CUR_NOTIFY_AD_SHOW, 0)
        }
    }

    override fun onActivityCreated(
        activity: Activity,
        savedInstanceState: Bundle?
    ) {
        if (activity is MdmRootActivity) {
            mMdmRootActivity = activity
        }
    }

    override fun onActivityStarted(activity: Activity) {
        if (activity is MdmRootActivity) {
            mMdmRootActivity = activity
        }
        if (!mAppMdmOpen && !mMdmCl && activity !is StartMdmActivity && activity !is MdmInputLinkActivity) {
            activity.startActivity(Intent(activity, StartMdmActivity::class.java).apply {
                activity.finish()
            })
        }
        mAppMdmOpen = true
        mListActivityList.add(activity)
    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {
        mListActivityList.remove(activity)
        mAppMdmOpen = mListActivityList.isNotEmpty()
    }

    override fun onActivitySaveInstanceState(
        activity: Activity,
        outState: Bundle
    ) {

    }

    override fun onActivityDestroyed(activity: Activity) {

    }

    private fun getAppFromValue() {
        if (BuildConfig.DEBUG) {
//            DataManagerMdmUtils.setDataKeyMdm(MDM_APP_FROM_VALUE, "mdmValue")
        }
        if (DataManagerMdmUtils.getDataKeyMdm(MDM_APP_FROM_VALUE, "").isEmpty()) {
            val clientMdm = InstallReferrerClient.newBuilder(applicationContext).build()
            clientMdm.startConnection(object : InstallReferrerStateListener {
                override fun onInstallReferrerSetupFinished(finish: Int) {
                    try {
                        DataManagerMdmUtils.setDataKeyMdm(MDM_APP_FROM_VALUE, "start")
                        if (finish == InstallReferrerClient.InstallReferrerResponse.OK) {
                            val result = clientMdm.installReferrer?.installReferrer ?: ""
                            if (result.contains("fb4a", true) || result.contains(
                                    "gclid",
                                    true
                                ) || result.contains(
                                    "facebook", true
                                ) || result.contains("MeteorDownloadVideo") || result.contains(
                                    "not%20set", true
                                ) || result.contains("youtubeads", true)
                            ) {
                                DataManagerMdmUtils.setDataKeyMdm(
                                    MDM_APP_FROM_VALUE, "mdmValue"
                                )
                            }
                        }
                    } catch (_: Exception) {
                    }
                }

                override fun onInstallReferrerServiceDisconnected() {
                }

            })
        }
    }
}